/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.misc.sap.jco.binding;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 代理类
 *
 * @author vacoor
 */
public class MapperProxy<I> implements InvocationHandler {
    private Class<I> mapperInterface;
    private Session session;
    private Map<Method, MapperMethod<I>> methodCache;

    public MapperProxy(Class<I> mapperInterface, Session session, Map<Method, MapperMethod<I>> methodCache) {
        this.mapperInterface = mapperInterface;
        this.session = session;
        this.methodCache = methodCache;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // Object 中的方法不代理
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }
        return cachedMapperMethod(method).execute(args);
    }

    protected MapperMethod cachedMapperMethod(Method method) {
        MapperMethod mapperMethod = methodCache.get(method);
        if (mapperMethod == null) {
            mapperMethod = new MapperMethod(mapperInterface, method, session);
            methodCache.put(method, mapperMethod);
        }
        return mapperMethod;
    }
}
